package com.cwh.taskcenter.domain.engine.rule.config;

import com.alibaba.qlexpress4.Express4Runner;
import com.alibaba.qlexpress4.InitOptions;
import com.alibaba.qlexpress4.runtime.function.CustomFunction;
import com.cwh.taskcenter.domain.engine.rule.function.QLExpressFunction;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Map;

/**
 * @author cwh
 */
@Configuration
public class QLExpressConfig implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Bean
    public Express4Runner express4Runner() {
        Express4Runner runner = new Express4Runner(InitOptions.DEFAULT_OPTIONS);
        runner.addAlias("AND","&&");
        runner.addAlias("OR","||");
        runner.addAlias("gt",">");
        runner.addAlias("lt","<");
        runner.addAlias("eq","==");
        runner.addAlias("ne","!=");
        runner.addAlias("ge",">=");
        runner.addAlias("le","<=");
        registerExpressFunction(runner);
        return runner;
    }

    /**
     * 注册函数
     * @param runner
     */
    private void registerExpressFunction(Express4Runner runner) {
        // 获取所有带有 @QLExpressFunction 注解的 Bean
        Map<String, Object> beans = applicationContext.getBeansWithAnnotation(QLExpressFunction.class);
        // 注册到 QLExpress
        for (Object bean : beans.values()) {
            QLExpressFunction annotation = bean.getClass().getAnnotation(QLExpressFunction.class);
            if (bean instanceof CustomFunction) {
                runner.addFunction(annotation.value(), (CustomFunction) bean);
            }
        }
    }

}
